<template>
  <div class="nutrition-log-container">
    <div class="page-header">
      <h1>饮食记录</h1>
    </div>
          <div class=" glass-card">
      <h2>营养摄入 summary</h2>

      <div class="summary-grid">
        <div class="summary-item">
          <span class="summary-label">总热量</span>
          <span class="summary-value">{{ totalCalories }} kcal</span>
          <div class="progress-bar" :style="{ width: caloriesPercentage + '%' }"></div>
          <span class="summary-goal">目标: {{ calorieGoal }} kcal</span>
        </div>
        <div class="summary-item">
          <span class="summary-label">蛋白质</span>
          <span class="summary-value">{{ totalProtein }} g</span>
          <div class="progress-bar protein" :style="{ width: proteinPercentage + '%' }"></div>
          <span class="summary-goal">目标: {{ proteinGoal }} g</span>
        </div>
        <div class="summary-item">
          <span class="summary-label">碳水化合物</span>
          <span class="summary-value">{{ totalCarbs }} g</span>
          <div class="progress-bar carbs" :style="{ width: carbsPercentage + '%' }"></div>
          <span class="summary-goal">目标: {{ carbsGoal }} g</span>
        </div>
        <div class="summary-item">
          <span class="summary-label">脂肪</span>
          <span class="summary-value">{{ totalFat }} g</span>
          <div class="progress-bar fat" :style="{ width: fatPercentage + '%' }"></div>
          <span class="summary-goal">目标: {{ fatGoal }} g</span>
        </div>
      </div>
      </div>
              </div>
    <div class="horizontal-sections">
      <!-- 添加饮食表单 -->
      <div class="add-meal-form glass-card">
            <div class="date-selector">
        <button class="date-btn" @click="changeDate(-1)">←</button>
        <span>{{ currentDate }}</span>
        <button class="date-btn" @click="changeDate(1)">→</button>
      </div>
      <h2>添加饮食</h2>
      <div class="form-grid">
        <div class="form-group">
          <label for="meal-type">餐次</label>
          <select id="meal-type" v-model="newMeal.type">
            <option value="breakfast">早餐</option>
            <option value="lunch">午餐</option>
            <option value="dinner">晚餐</option>
            <option value="snack">加餐</option>
          </select>
        </div>
        <div class="form-group">
          <label for="food-name">食物名称</label>
          <input type="text" id="food-name" v-model="newMeal.name" placeholder="输入食物名称">
        </div>
        <div class="form-group">
          <label for="food-calories">热量 (kcal)</label>
          <input type="number" id="food-calories" v-model.number="newMeal.calories" placeholder="0" min="0">
        </div>
        <div class="form-group">
          <label for="food-protein">蛋白质 (g)</label>
          <input type="number" id="food-protein" v-model.number="newMeal.protein" placeholder="0" min="0">
        </div>
        <div class="form-group">
          <label for="food-carbs">碳水 (g)</label>
          <input type="number" id="food-carbs" v-model.number="newMeal.carbs" placeholder="0" min="0">
        </div>
        <div class="form-group">
          <label for="food-fat">脂肪 (g)</label>
          <input type="number" id="food-fat" v-model.number="newMeal.fat" placeholder="0" min="0">
        </div>
      </div>
      <button class="btn-primary" @click="addMeal">添加</button>
    </div>

      <!-- 饮食记录列表 -->
      <div class="meal-records glass-card">
      <h2>今日饮食</h2>
      <div v-if="mealsByType.breakfast.length > 0" class="meal-type-section">
        <h3>早餐</h3>
        <div class="meal-items">
          <div v-for="(meal, index) in mealsByType.breakfast" :key="meal.id" class="meal-item">
            <div class="meal-info">
              <span class="meal-name">{{ meal.name }}</span>
              <span class="meal-macros">{{ meal.calories }}kcal · {{ meal.protein }}P · {{ meal.carbs }}C · {{ meal.fat }}F</span>
            </div>
            <button class="delete-btn" @click="deleteMeal('breakfast', index)">×</button>
          </div>
        </div>
      </div>

      <div v-if="mealsByType.lunch.length > 0" class="meal-type-section">
        <h3>午餐</h3>
        <div class="meal-items">
          <div v-for="(meal, index) in mealsByType.lunch" :key="meal.id" class="meal-item">
            <div class="meal-info">
              <span class="meal-name">{{ meal.name }}</span>
              <span class="meal-macros">{{ meal.calories }}kcal · {{ meal.protein }}P · {{ meal.carbs }}C · {{ meal.fat }}F</span>
            </div>
            <button class="delete-btn" @click="deleteMeal('lunch', index)">×</button>
          </div>
        </div>
      </div>

      <div v-if="mealsByType.dinner.length > 0" class="meal-type-section">
        <h3>晚餐</h3>
        <div class="meal-items">
          <div v-for="(meal, index) in mealsByType.dinner" :key="meal.id" class="meal-item">
            <div class="meal-info">
              <span class="meal-name">{{ meal.name }}</span>
              <span class="meal-macros">{{ meal.calories }}kcal · {{ meal.protein }}P · {{ meal.carbs }}C · {{ meal.fat }}F</span>
            </div>
            <button class="delete-btn" @click="deleteMeal('dinner', index)">×</button>
          </div>
        </div>
      </div>

      <div v-if="mealsByType.snack.length > 0" class="meal-type-section">
        <h3>加餐</h3>
        <div class="meal-items">
          <div v-for="(meal, index) in mealsByType.snack" :key="meal.id" class="meal-item">
            <div class="meal-info">
              <span class="meal-name">{{ meal.name }}</span>
              <span class="meal-macros">{{ meal.calories }}kcal · {{ meal.protein }}P · {{ meal.carbs }}C · {{ meal.fat }}F</span>
            </div>
            <button class="delete-btn" @click="deleteMeal('snack', index)">×</button>
          </div>
        </div>
      </div>

      <div v-if="isMealsEmpty" class="no-meals">
        <p>今日暂无饮食记录，开始添加吧！</p>
      </div>
    </div>


  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useNutritionStore } from '@/stores/nutrition';

const nutritionStore = useNutritionStore();

// 日期管理
const currentDate = ref(new Date().toLocaleDateString('zh-CN', { year: 'numeric', month: 'long', day: 'numeric' }));
const selectedDate = ref(new Date());

// 表单数据
const newMeal = ref({
  type: 'breakfast',
  name: '',
  calories: 0,
  protein: 0,
  carbs: 0,
  fat: 0
});

// 从store获取营养目标
const calorieGoal = computed(() => nutritionStore.nutritionGoals.calories);
const proteinGoal = computed(() => nutritionStore.nutritionGoals.protein);
const carbsGoal = computed(() => nutritionStore.nutritionGoals.carbs);
const fatGoal = computed(() => nutritionStore.nutritionGoals.fat);

// 初始化
onMounted(() => {
  nutritionStore.loadMeals(selectedDate.value);
});

// 按餐次分组的饮食记录
const mealsByType = computed(() => ({
  breakfast: nutritionStore.meals.filter(meal => meal.type === 'breakfast'),
  lunch: nutritionStore.meals.filter(meal => meal.type === 'lunch'),
  dinner: nutritionStore.meals.filter(meal => meal.type === 'dinner'),
  snack: nutritionStore.meals.filter(meal => meal.type === 'snack')
}));

// 检查是否有饮食记录
const isMealsEmpty = computed(() => {
  return Object.values(mealsByType.value).every(meals => meals.length === 0);
});

// 计算总营养摄入
const totalCalories = computed(() => {
  return Math.max(0, nutritionStore.meals.reduce((sum, meal) => sum + meal.calories, 0));
});

const totalProtein = computed(() => {
  return Math.max(0, nutritionStore.meals.reduce((sum, meal) => sum + meal.protein, 0));
});

const totalCarbs = computed(() => {
  return Math.max(0, nutritionStore.meals.reduce((sum, meal) => sum + meal.carbs, 0));
});

const totalFat = computed(() => {
  return Math.max(0, nutritionStore.meals.reduce((sum, meal) => sum + meal.fat, 0));
});

// 计算进度百分比
const caloriesPercentage = computed(() => Math.min(Math.round((totalCalories.value / calorieGoal.value) * 100), 100));
const proteinPercentage = computed(() => Math.min(Math.round((totalProtein.value / proteinGoal.value) * 100), 100));
const carbsPercentage = computed(() => Math.min(Math.round((totalCarbs.value / carbsGoal.value) * 100), 100));
const fatPercentage = computed(() => Math.min(Math.round((totalFat.value / fatGoal.value) * 100), 100));

// 方法
const changeDate = (days) => {
  selectedDate.value.setDate(selectedDate.value.getDate() + days);
  currentDate.value = selectedDate.value.toLocaleDateString('zh-CN', { year: 'numeric', month: 'long', day: 'numeric' });
  nutritionStore.loadMeals(selectedDate.value);
};

const addMeal = () => {
  if (!newMeal.value.name || newMeal.value.calories <= 0) {
    alert('请输入有效的食物名称和热量');
    return;
  }

  nutritionStore.addMeal({
    ...newMeal.value,
    date: selectedDate.value
  });

  // 重置表单
  newMeal.value = {
    type: 'breakfast',
    name: '',
    calories: 0,
    protein: 0,
    carbs: 0,
    fat: 0
  };
};

const deleteMeal = (type, index) => {
  const mealToDelete = nutritionStore.meals.find(m => m.id === mealsByType.value[type][index].id);
  nutritionStore.deleteMeal(mealToDelete);
};
</script>

<style scoped>
.nutrition-log-container {
  padding: 1rem;
  margin: 230px auto 0;
  padding-bottom: 92px;
}

.horizontal-sections {
  display: flex;
  gap: 1rem;
  margin-bottom: 2rem;
}

@media (max-width: 768px) {
  .horizontal-sections {
    flex-direction: column;
  }
}

.horizontal-sections .glass-card {
  margin-bottom: 0;
}

.add-meal-form,
.meal-records {
  flex: 1;
  min-width: 300px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 2rem;
}

.date-selector {
  display: flex;
  align-items: center;
  gap: 1rem;
}

.date-btn {
  background: none;
  border: none;
  font-size: 1.2rem;
  cursor: pointer;
  color: #2d3436;
}

.add-meal-form h2,
.meal-records h2,
.nutrition-summary h2 {
  margin-bottom: 1.5rem;
  color: #2d3436;
  font-size: 1.5rem;
}

.form-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 1rem;
  margin-bottom: 1.5rem;
}

.form-group label {
  display: block;
  margin-bottom: 0.5rem;
  color: white;
  font-size: 0.9rem;
}

.form-group input,
.form-group select {
  width: 100%;
  padding: 0.8rem;
  border: none;
  border-radius: 8px;
  background-color: rgba(255, 255, 255, 0.7);
  backdrop-filter: blur(5px);
}

.btn-primary {
  background-color: #00cec9;
  color: white;
  border: none;
  padding: 0.8rem 1.5rem;
  border-radius: 8px;
  cursor: pointer;
  font-weight: bold;
  transition: all 0.3s ease;
}

.btn-primary:hover {
  background-color: #00b8b3;
  transform: translateY(-2px);
}

.meal-type-section {
  margin-bottom: 1.5rem;
}

.meal-type-section h3 {
  margin-bottom: 0.8rem;
  color: #2d3436;
  font-size: 1.2rem;
  padding-bottom: 0.3rem;
  border-bottom: 1px solid rgba(255, 255, 255, 0.3);
}

.meal-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0.8rem 0;
  border-bottom: 1px dashed rgba(255, 255, 255, 0.2);
}

.meal-info {
  display: flex;
  flex-direction: column;
}

.meal-name {
  font-weight: 500;
  color: white;
}

.meal-macros {
  font-size: 0.8rem;
  color: white;
}

.delete-btn {
  background: none;
  border: none;
  color: #d63031;
  cursor: pointer;
  font-size: 1rem;
  opacity: 0.7;
  transition: opacity 0.3s ease;
}

.delete-btn:hover {
  opacity: 1;
}

.no-meals {
  text-align: center;
  padding: 2rem;
  color: white;
}

.summary-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 1.5rem;
}

@media (max-width: 768px) {
  .summary-grid {
    grid-template-columns: repeat(2, 1fr);
  }
}

.summary-item {
  display: flex;
  flex-direction: column;
  gap: 1.3rem;
  padding: 1.2rem;
  min-height: 120px;
}

.summary-label {
  font-size: 0.9rem;
  color: white;
}

.summary-value {
  font-size: 1.5rem;
  font-weight: bold;
  color: white;
}

.progress-bar {
  height: 8px;
  background-color: rgba(255, 255, 255, 0.3);
  border-radius: 4px;
  overflow: hidden;
  background-image: linear-gradient(to right, #00cec9, #00cec9);
}

.progress-bar.protein {
  background-image: linear-gradient(to right, #74b9ff, #74b9ff);
}

.progress-bar.carbs {
  background-image: linear-gradient(to right, #ffeaa7, #ffeaa7);
}

.progress-bar.fat {
  background-image: linear-gradient(to right, #ff7675, #ff7675);
}

.summary-goal {
  font-size: 0.8rem;
  color: white;
  text-align: right;
}

.glass-card {
  background: rgba(255, 255, 255, 0.25);
  backdrop-filter: blur(10px);
  border-radius: 16px;
  padding: 1.5rem;
  margin-bottom: 2rem;
  box-shadow: 0 8px 32px 0 rgba(31, 38, 135, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.18);
}

@media (max-width: 400px) {
  .nutrition-log-container {
  padding: 2.13vw;
  margin-top: 21.33vw;
  overflow-x: hidden;
}

.btn-primary {
  padding: 2.13vw 3.47vw;
  font-size: 3.84vw;
}
  .form-grid {
    grid-template-columns: 1fr;
  }
  .glass-card {
    padding: 1rem;
  }
  .meal-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 0.5rem;
  }
  .summary-grid {
  grid-template-columns: 1fr;
  gap: 2.13vw;
}

.meal-name {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 150px;
}

.meal-macros {
  font-size: 0.85rem;
}

* {
  box-sizing: border-box;
}
}
</style>